<?php
declare (strict_types=1);

namespace app\admin\controller\user;

use think\response\Json;
use app\admin\controller\Controller;
use app\admin\model\user\Grade as GradeModel;
use app\admin\model\user\GradeLog as GradeLogModel;
use app\common\enum\user\grade\log\ChangeType as ChangeTypeEnum;
/**
 * 会员等级
 * Class Grade
 * @package app\admin\controller\user
 */
class Grade extends Controller
{
    /**
     * 列表
     * @return Json
     */
    public function lists(): Json
    {
        $model = new GradeModel;
        $list = $model->getList($this->request->param())->toArray();
        return $this->renderSuccess([
            'total' => $list['total'],
            'items' => $list['data']
        ]);
    }

    /**
     * 全部记录
     * @return Json
     */
    public function all(): Json
    {
        $model = new GradeModel;
        $list = $model->getAll($this->request->param())->toArray();
        return $this->renderSuccess($list);
    }
    /**
     * 设置状态
     * @return Json
     */
    public function setstatus()
    {
        $params = $this->postData();
        $model = GradeModel::detail($params['id']);
        if ($model->edit(['status' => $params['status'], 'weight' => $model->weight])) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 添加
     * @return Json
     */
    public function add(): Json
    {
        $model = new GradeModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑
     * @param int $id
     * @return Json
     */
    public function edit(int $id): Json
    {
        $model = GradeModel::detail($id);
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除会员等级
     * @param int $gradeId
     * @return Json
     */
    public function delete(int $gradeId): Json
    {
        $model = GradeModel::detail($gradeId);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 等级变更明细
     * @return Json
     */
    public function log(): Json
    {
        $model = new GradeLogModel;
        $list = $model->getList($this->request->param())->toArray();
        return $this->renderSuccess([
            'total' => $list['total'],
            'items' => $list['data']
        ]);
    }
    /**
     * 变更类型
     * @return Json
     */
    public function getChangeType(): Json
    {
        $list = ChangeTypeEnum::data();
        $res = [];
        foreach ($list as $key => $value) {
            $res[] = $value;
        }
        return $this->renderSuccess($res);
    }
}
